<template>
  <div class="bar-chart-wrapper">
    <div ref="barChart" class="chart-container"></div>
    <div v-if="loading" class="chart-loading">
      <el-icon class="is-loading"><Loading /></el-icon>
      <span>加载中...</span>
    </div>
    <div v-if="!loading && isEmpty" class="chart-empty">
      <el-empty description="暂无数据" />
    </div>
  </div>
</template>

<script setup>
import { nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { Loading } from '@element-plus/icons-vue'
import { postList } from "@/uses/handleData.js"

const props = defineProps({
  // 图表标题
  title: {
    type: String,
    default: ''
  },
  // 数据模型
  model: {
    type: String,
    required: false
  },
  // 静态数据（当不使用 model 时）
  data: {
    type: Array,
    default: () => []
  },
  // X轴数据字段
  xAxisKey: {
    type: String,
    default: 'name'
  },
  // Y轴数据字段（可以是单个字段或多个字段数组）
  yAxisKey: {
    type: [String, Array],
    default: 'value'
  },
  // 系列名称（当有多个系列时）
  seriesNames: {
    type: Array,
    default: () => []
  },
  // 图表高度
  height: {
    type: String,
    default: '350px'
  },
  // 柱子宽度
  barWidth: {
    type: String,
    default: '60%'
  },
  // 是否显示图例
  showLegend: {
    type: Boolean,
    default: true
  },
  // 图例位置
  legendPosition: {
    type: String,
    default: 'top', // top, bottom, left, right
    validator: (value) => ['top', 'bottom', 'left', 'right'].includes(value)
  },
  // 是否显示网格线
  showGrid: {
    type: Boolean,
    default: true
  },
  // 自定义颜色
  colors: {
    type: Array,
    default: () => [
      '#5470c6',
      '#91cc75',
      '#fac858',
      '#ee6666',
      '#73c0de',
      '#3ba272',
      '#fc8452',
      '#9a60b4',
      '#ea7ccc'
    ]
  },
  // 动画效果
  animation: {
    type: Boolean,
    default: true
  },
  // 是否显示圆角
  borderRadius: {
    type: Number,
    default: 0
  },
  // 是否横向显示
  horizontal: {
    type: Boolean,
    default: false
  },
  // 是否堆叠
  stack: {
    type: Boolean,
    default: false
  },
  // Y轴名称
  yAxisName: {
    type: String,
    default: ''
  },
  // X轴名称
  xAxisName: {
    type: String,
    default: ''
  },
  // 是否显示标签
  showLabel: {
    type: Boolean,
    default: false
  }
})

const barChart = ref(null)
let chartInstance = null
const loading = ref(false)
const isEmpty = ref(false)

// 获取图例配置
const getLegendConfig = () => {
  if (!props.showLegend) {
    return { show: false }
  }

  const baseConfig = {
    type: 'scroll',
    textStyle: {
      fontSize: 12,
      color: '#666'
    },
    pageTextStyle: {
      color: '#999'
    }
  }

  const positions = {
    top: { top: '10', left: 'center', orient: 'horizontal' },
    bottom: { bottom: '10', left: 'center', orient: 'horizontal' },
    left: { left: '10', top: 'center', orient: 'vertical' },
    right: { right: '10', top: 'center', orient: 'vertical' }
  }

  return {
    ...baseConfig,
    ...positions[props.legendPosition]
  }
}

// 获取网格配置
const getGridConfig = () => {
  const baseGrid = {
    left: '3%',
    right: '4%',
    bottom: '3%',
    top: props.title ? '80' : '60',
    containLabel: true
  }

  if (props.legendPosition === 'left') {
    baseGrid.left = '15%'
  } else if (props.legendPosition === 'right') {
    baseGrid.right = '15%'
  } else if (props.legendPosition === 'bottom') {
    baseGrid.bottom = '15%'
  }

  return baseGrid
}

// 初始化图表配置
const getOption = (xAxisData, seriesData) => {
  const option = {
    color: props.colors,
    title: props.title ? {
      text: props.title,
      left: 'center',
      top: props.legendPosition === 'top' ? '40' : '10',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#333'
      }
    } : null,
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      backgroundColor: 'rgba(50, 50, 50, 0.9)',
      borderColor: '#333',
      borderWidth: 1,
      textStyle: {
        color: '#fff'
      }
    },
    legend: getLegendConfig(),
    grid: getGridConfig(),
    animation: props.animation,
    animationDuration: 1000,
    animationEasing: 'cubicOut'
  }

  if (props.horizontal) {
    // 横向柱状图
    option.xAxis = {
      type: 'value',
      name: props.xAxisName,
      splitLine: {
        show: props.showGrid,
        lineStyle: {
          color: '#e5e5e5',
          type: 'dashed'
        }
      }
    }
    option.yAxis = {
      type: 'category',
      name: props.yAxisName,
      data: xAxisData,
      axisLabel: {
        fontSize: 12,
        color: '#666'
      }
    }
  } else {
    // 纵向柱状图
    option.xAxis = {
      type: 'category',
      name: props.xAxisName,
      data: xAxisData,
      axisLabel: {
        fontSize: 12,
        color: '#666',
        interval: 0,
        rotate: xAxisData.length > 8 ? 45 : 0
      }
    }
    option.yAxis = {
      type: 'value',
      name: props.yAxisName,
      splitLine: {
        show: props.showGrid,
        lineStyle: {
          color: '#e5e5e5',
          type: 'dashed'
        }
      }
    }
  }

  option.series = seriesData.map((series, index) => ({
    name: series.name,
    type: 'bar',
    data: series.data,
    barWidth: props.barWidth,
    stack: props.stack ? 'total' : undefined,
    itemStyle: {
      borderRadius: props.borderRadius
    },
    label: {
      show: props.showLabel,
      position: props.horizontal ? 'right' : 'top',
      fontSize: 12,
      color: '#666'
    },
    emphasis: {
      itemStyle: {
        shadowBlur: 10,
        shadowOffsetX: 0,
        shadowColor: 'rgba(0, 0, 0, 0.5)'
      }
    },
    animationDelay: (idx) => idx * 50
  }))

  return option
}

// 初始化图表
const initChart = (xAxisData, seriesData) => {
  if (!barChart.value) return

  // 如果实例已存在，先销毁
  if (chartInstance) {
    chartInstance.dispose()
  }

  chartInstance = echarts.init(barChart.value)
  chartInstance.setOption(getOption(xAxisData, seriesData))

  // 添加窗口大小改变监听
  window.addEventListener('resize', handleResize)
}

// 处理窗口大小改变
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 加载数据
const loadData = async () => {
  try {
    loading.value = true
    isEmpty.value = false

    let xAxisData = []
    let seriesData = []

    // 如果有静态数据，使用静态数据
    if (props.data && props.data.length > 0) {
      xAxisData = props.data.map(item => item[props.xAxisKey])

      // 处理多系列数据
      if (Array.isArray(props.yAxisKey)) {
        seriesData = props.yAxisKey.map((key, index) => ({
          name: props.seriesNames[index] || key,
          data: props.data.map(item => item[key] || 0)
        }))
      } else {
        seriesData = [{
          name: props.seriesNames[0] || props.yAxisName || '数据',
          data: props.data.map(item => item[props.yAxisKey] || 0)
        }]
      }
    }
    // 否则从 API 加载
    else if (props.model) {
      let res = await postList(props.model, {})
      if (res.code === 200 && res.data && res.data.length > 0) {
        xAxisData = res.data.map(item => item[props.xAxisKey])

        // 处理多系列数据
        if (Array.isArray(props.yAxisKey)) {
          seriesData = props.yAxisKey.map((key, index) => ({
            name: props.seriesNames[index] || key,
            data: res.data.map(item => item[key] || 0)
          }))
        } else {
          seriesData = [{
            name: props.seriesNames[0] || props.yAxisName || '数据',
            data: res.data.map(item => item[props.yAxisKey] || 0)
          }]
        }
        console.info('柱状图数据:', { xAxisData, seriesData })
      }
    }

    // 检查是否有数据
    if (xAxisData.length === 0 || seriesData.length === 0) {
      isEmpty.value = true
      return
    }

    await nextTick()
    initChart(xAxisData, seriesData)
  } catch (error) {
    console.error('加载柱状图数据失败:', error)
    isEmpty.value = true
  } finally {
    loading.value = false
  }
}

// 监听数据变化
watch(() => props.data, () => {
  if (props.data && props.data.length > 0) {
    loadData()
  }
}, { deep: true })

// 监听配置变化
watch(() => [
  props.colors,
  props.barWidth,
  props.showLegend,
  props.legendPosition,
  props.showLabel,
  props.horizontal,
  props.stack
], () => {
  if (chartInstance) {
    loadData()
  }
}, { deep: true })

onMounted(() => {
  loadData()
})

onUnmounted(() => {
  if (chartInstance) {
    window.removeEventListener('resize', handleResize)
    chartInstance.dispose()
    chartInstance = null
  }
})

// 暴露刷新方法
defineExpose({
  refresh: loadData,
  getInstance: () => chartInstance
})
</script>

<style scoped lang="scss">
.bar-chart-wrapper {
  position: relative;
  width: 100%;
  height: v-bind(height);

  .chart-container {
    width: 100%;
    height: 100%;
  }

  .chart-loading {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    color: #999;
    font-size: 14px;

    .el-icon {
      font-size: 32px;
    }
  }

  .chart-empty {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 100%;
  }
}
</style>

